package com.first.group.authserver.service.impl;

import com.first.group.authserver.entity.UserEntity;
import com.first.group.common.utils.PageUtils;
import com.first.group.common.utils.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.first.group.authserver.dao.AddressDao;
import com.first.group.authserver.entity.AddressEntity;
import com.first.group.authserver.service.AddressService;


@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressDao, AddressEntity> implements AddressService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AddressEntity> page = this.page(
                new Query<AddressEntity>().getPage(params),
                new QueryWrapper<AddressEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<AddressEntity> treeList() {

        //先查出所有的父级地址
        List<AddressEntity> parentIds = baseMapper.selectList(new QueryWrapper<AddressEntity>().eq("address_parent_id", 0));
        //根据父类id查找下一级
        for (AddressEntity parentId : parentIds) {
            getChildren(parentId);
        }
        return parentIds;
    }

    @Override
    public List<AddressEntity> getByIds(List<Long> ids) {

        return baseMapper.selectBatchIds(ids);
    }

    //利用递归,寻找下一级的数据并放入集合中
    private void getChildren(AddressEntity parentId) {
        //先判断当前等级是否有下一级
        List<AddressEntity> nextTree = baseMapper.selectList(new QueryWrapper<AddressEntity>().eq("address_parent_id", parentId.getAddressId()));
        if (nextTree.size() > 0) {
            //此时有下一级
            //使用递归
            for (AddressEntity addressEntity : nextTree) {
                getChildren(addressEntity);
            }
            parentId.setChildren(nextTree);
        }
    }

}